package cn.itbeien.manager.controller;

import cn.itbeien.core.enums.*;
import cn.itbeien.core.util.LoadBalancer;
import cn.itbeien.entity.QrCodeMerchant;
import cn.itbeien.manager.service.IMerchantService;
import cn.itbeien.response.CommonResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
//import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import cn.itbeien.vo.PaymentVO;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author beien
 * @date 2024-03-16 15:35
 * Copyright© 2024 beien
 */
@RestController
@RequestMapping("pay")
@Slf4j
public class PaymentController {

    @Autowired
    private IMerchantService merchantService;

    private RestTemplate restTemplate;

    @Bean  //交由spring容器管理
    //@LoadBalanced  //添加负载均衡功能
    public RestTemplate restTemplate(){
        restTemplate = new RestTemplate();
        return restTemplate;
    }

    @NacosInjected
    private NamingService namingService;

    @Autowired
    private LoadBalancer loadBalancer;


    /**
     * 预支付接口 H5 jsapi
     * @RequestBody String data, post json
     * @RequestParam("data")String str request url
     * @Param  paymentVO H5页面表单方式提交
     * 当使用@RestController时返回数据不需要使用@ResponseBody
     * @return
     */
    @PostMapping("doPay")
    public CommonResponse doPay(PaymentVO paymentVO){
        CommonResponse commonResponse = new CommonResponse();

        try{

            validateParam(paymentVO);
            //定义一个参数校验的公共方法，用于校验不能为空的参数，如果参数为空则返回异常信息
            //从枚举中获取支付产品和支付场景
            //支付宝
            /**
             * 设置支付产品和支付场景
             */
            if(null != paymentVO.getUserAngent() && paymentVO.getUserAngent().equals(UserAngentEnum.AlipayUserAngent.getCode())){
                paymentVO.setProductCode(PayEnum.AliPay.getPay());
                paymentVO.setPayType(PayTypeEnum.AliPay.getPayType());
            }else if(null != paymentVO.getUserAngent() && paymentVO.getUserAngent().equals(UserAngentEnum.WechatUserAngent.getCode())){
             //微信
                paymentVO.setProductCode(PayEnum.WechatPay.getPay());
                paymentVO.setPayType(PayTypeEnum.WechatPay.getPayType());
            }else if(null != paymentVO.getUserAngent() && paymentVO.getUserAngent().equals(UserAngentEnum.CloudPayUserAngent.getCode())){
              //云闪付
                paymentVO.setProductCode(PayEnum.UnionPay.getPay());
                paymentVO.setPayType(PayTypeEnum.UnionPay.getPayType());
            }
            //交易码 pay
            paymentVO.setInterfaceCode(InterfaceCodeEnum.PayInterface.getCode());

            //设置商户编码
            QrCodeMerchant qrCodeMerchant =  merchantService.findMerchantByCode(paymentVO.getQrCode());
            paymentVO.setMerchantCode(qrCodeMerchant.getMerchantCode());

            //对象转成JSONObject
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(paymentVO));


            // 服务发现 Instance(微服务---支付服务)
            List<Instance> instances  = namingService.getAllInstances("payment","dev");

            //List<Instance> pay_instances  = namingService.getAllInstances("pay_front","dev");
            // 创建服务器列表(list集合)
            List<String> servers = new ArrayList<>();
            for(Instance instance:instances){
                String orderServiceUrl="http://"+instance.getIp()+":"+instance.getPort()+"/";
                servers.add(orderServiceUrl);
            }

            //设置服务器列表(list集合)
            loadBalancer.setServers(servers);

            //  orderServiceUrl用List存储
            // @LoadBalanced 随机(使用随机函数生成0-list.size-1)，轮询  %取模 index=(index+1)%list.size
            //发起微服务调用
            //orderServiceUrl
            final String orderServiceUrl =   loadBalancer.roundRobin();


            //发起微服务调用
            commonResponse =  restTemplate.postForObject(orderServiceUrl+ ServiceInstanceEnum.PayServiceURL.getCode(),jsonObject, CommonResponse.class);

            System.out.println(commonResponse);

        }catch(Exception e){
            commonResponse.setMessage(e.getMessage());
            commonResponse.setCode(SystemEnum.SYSTEM_PARAMS_ERROR.getCode());
           log.error("系统异常:{}",e);
        }


        return commonResponse;

    }

    /**
     * 公共参数校验方法
     */
    private void validateParam(PaymentVO paymentVO) throws Exception{
        /**
         * 金额
         * 二维码code
         * 前端传入产品标识userAngent
         *
         */

        if(null == paymentVO.getAmount() || "".equals(paymentVO.getAmount())){
            throw new Exception(SystemEnum.SYSTEM_PARAMS_ERROR.getMessage());
        }


        if(null == paymentVO.getQrCode() || "".equals(paymentVO.getQrCode())){
            throw new Exception(SystemEnum.SYSTEM_PARAMS_ERROR.getMessage());
        }

        if(null == paymentVO.getUserAngent() || "".equals(paymentVO.getUserAngent())){
            throw new Exception(SystemEnum.SYSTEM_PARAMS_ERROR.getMessage());
        }

    }

}
